#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/queue.h>
#include "common.h"

struct TVTS_DLL_ENTRY {
	char* data;
	LIST_ENTRY(TVTS_DLL_ENTRY) entries;
};

LIST_HEAD(TVTS_DLL_HEAD, TVTS_DLL_ENTRY);

int main(int argc, char* argv[]) {
	char buf[MAXLINE];

	// SLL
	struct TVTS_DLL_ENTRY *np = 0, *n1 = 0, *n2 = 0;
	struct TVTS_DLL_HEAD head;
	LIST_INIT(&head);

	// insert
	printf("Start insertion ...\n");
	int i;
	for (i = 1; i < argc; i ++) {
		char* arg = argv[i];
		snprintf(buf, MAXLINE, "%s-%d-%s", arg, i, arg);
		char* arg_cp = cp_str(buf);
		printf("> %d: %s => %s\n", i, arg, arg_cp);

		np = malloc(sizeof(struct TVTS_DLL_ENTRY));
		np->data = arg_cp;

		n2 = np;
		if (1 == i) {
			LIST_INSERT_HEAD(&head, n2, entries);
		} else {
			LIST_INSERT_AFTER(n1, n2, entries);
		}

		n1 = n2;
	}
	printf("Insertions done.\n");

	// iterate
	printf("Start iteration ...\n");
	i = 0;
	LIST_FOREACH(np, &head, entries) {
    	printf("%d: %s\n", ++i, np->data);
	}
	printf("Iteration done.\n");

	// destruct
	printf("Cleaning ...\n");
	n1 = LIST_FIRST(&head);
	while (n1 != NULL) {
	   n2 = LIST_NEXT(n1, entries);
	   free(n1);
	   n1 = n2;
	}
    LIST_INIT(&head);
    printf("Cleaning done.\n");
}
